package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserManager userManager;

    // 保存用户
    @PostMapping("/user/save")
    public ResponseEntity save(@RequestBody User user) {
        return userManager.save(user);
    }

    // 根据手机号查询
    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone) {
        return userManager.findByPhone(phone);
    }

    // 发送验证码
    @PostMapping("/user/login")
    public ResponseEntity sendSmsCode(@RequestBody Map<String, String> map) {



        // 1.接收参数
        String phone = map.get("phone");
        // 2.调用manager处理
        return userManager.sendSmsCode(phone);
    }

    // 注册、登录
    @PostMapping("/user/loginVerification")
    public ResponseEntity regAndLogin(@RequestBody Map<String, String> map) {
        // 1.接收参数
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");
        // 2.调用mananger并返回结果
        return userManager.regAndLogin(phone, verificationCode);
    }

    // 完善用户基本信息
    @PostMapping("/user/loginReginfo")
    public ResponseEntity saveUserInfoBase(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {
        return userManager.saveUserInfoBase(userInfo, token);
    }

    // 完善用户头像信息
    @PostMapping({"/user/loginReginfo/head","/users/header"})
    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        return userManager.saveUserInfoHead(headPhoto, token);
    }

    // 查询用户信息
    @GetMapping("/users")
    public ResponseEntity findUserInfoById(Long userID, Long huanxinID, @RequestHeader("Authorization") String token) {
        if (userID != null) { //  1.如果userID不为空,就按照userID查询
            return userManager.findUserInfoById(userID);
        } else if (huanxinID != null) {    //  2.如果userID为空,huanxinID不为空,就按照huanxinID查询
            return userManager.findUserInfoById(huanxinID);
        }else{//  3.如果上面两个都为空,就从token中获取登录用户id查询
            User user = userManager.findUserByToken(token);
            return userManager.findUserInfoById(user.getId());
        }
    }

    // 更新用户基本信息
    @PutMapping("/users")
    public ResponseEntity updateUserInfoBase(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        return userManager.updateUserInfoBase(userInfo,token);
    }




}
